#!/usr/bin/python
# -*- coding: UTF-8 -*-
import json
from collections import OrderedDict

import urllib
from urllib import urlopen

import sqlite3

import RoomManage

KEY_SESSION_KEY = "session_key"
KEY_OPEN_ID = "openid"
KEY_USER_CODE = "userCode"
KEY_ERROR_MSG = "errmsg"

KEY_USER_NAME = "userName"
KEY_USER_ICON_URL = "iconURL"
KEY_USER_SCORE = "userScore"
KEY_USER_ROUND = "userRound"

DATABASE_NAME = "Take6DataBase.db"

class MessageType:
    MESSAGE_USER_DATA = "user_data"

class UserData:
    OpenID = ""
    Name = ""
    Score = 0
    Round = 0
    URL = ""

def checkIsUserDataMessage(strMessage):
    try:
        dicJsonMessage = json.loads(strMessage)
        if dicJsonMessage.has_key(RoomManage.KEY_MESSAGE_TYPE):
            strMessageType = dicJsonMessage[RoomManage.KEY_MESSAGE_TYPE]
            if strMessageType == MessageType.MESSAGE_USER_DATA:
                return True
            else:
                return False
        else:
            return False
    
    except ValueError:
        print "strMessage is not json"
        return False
    
    except Exception,e:
        print 'error:',e
        return False

def getUserCode(strMessage):
    try:
        dicJsonMessage = json.loads(strMessage)
        return dicJsonMessage[KEY_USER_CODE]
    
    except Exception,e:
        print 'error:',e
        return False

def getUserDataMessage(userDataManager):
    try:
        dicUserDataMessage = OrderedDict()
        dicUserDataMessage[RoomManage.KEY_MESSAGE_TYPE] = MessageType.MESSAGE_USER_DATA
        dicUserDataMessage[KEY_USER_NAME] = userDataManager.getUserName()
        dicUserDataMessage[KEY_USER_ICON_URL] = userDataManager.getUserURL()
        dicUserDataMessage[KEY_USER_SCORE] = userDataManager.getUserScore()
        dicUserDataMessage[KEY_USER_ROUND] = userDataManager.getUserRound()
    
        strJsonMessage = json.dumps(dicUserDataMessage)
        return strJsonMessage
    
    except Exception,e:
        print 'error:',e
        return False

class UserDataManage:

    def __init__(self, code):
        self.m_bHasDataInDataBase = False
        self.m_UserData = None
        
        try:
            self.m_bHasDataInDataBase = False
        
            params = urllib.urlencode({'appid':'wxf2ad5dd9088db987','secret':'86ec85a0de34d1ab7b7baa935f7ffc7b','js_code':code,'grant_type':'authorization_code'})
            result = urlopen('https://api.weixin.qq.com/sns/jscode2session?%s',params)
            strMessage = result.read()
            
            dicJsonResult = json.loads(strMessage)
            
            openid = ''
            if dicJsonResult.has_key(KEY_OPEN_ID):
                openid = dicJsonResult[KEY_OPEN_ID]
                name = "player"
                score = 0
                round = 0
                url = ""

                conn = sqlite3.connect(DATABASE_NAME)
                c = conn.cursor()
                
                slectSQL = "select * from USER where OPEN_ID='%s'" % openid
                cursor = c.execute(str(slectSQL))

                result = cursor.fetchall()
                if len(result) == 0:
                    # insert
                    insertSQL = "INSERT INTO USER (OPEN_ID,NAME,SCORE,ROUND) VALUES ('%s', 'player', 0, 0)" % openid
                    c.execute(str(insertSQL));
                    conn.commit()
                    print "Player insert new User OK"
                
                else:
                    for row in result:
                        print "OPEN_ID = ", row[0]
                        print "NAME = ", row[1]
                        print "SCORE = ", row[2]
                        print "ROUND = ", row[3],
                        print "URL = ", row[4], "\n"
            
                        name = row[1]
                        score = row[2]
                        round = row[3]
                        url = row[4]
            
                conn.close()
                
                self.m_UserData = UserData()
                self.m_UserData.OpenID = openid
                self.m_UserData.Name = name
                self.m_UserData.Score = score
                self.m_UserData.Round = round
                self.m_UserData.URL = url
                
                self.m_bHasDataInDataBase = True
            else:
                print "get openid failed : ", strMessage
                print "errmsg : ", dicJsonResult[KEY_ERROR_MSG]
                
                self.m_bHasDataInDataBase = False
        except Exception,e:
            print 'error:',e
        
    def getUserName(self):
        if self.m_UserData != None :
            return self.m_UserData.Name
        else :
            return ""

    def getUserScore(self):
        if self.m_UserData != None :
            return self.m_UserData.Score
        else :
            return 0

    def getUserRound(self):
        if self.m_UserData != None :
            return self.m_UserData.Round
        else :
            return 0

    def getUserURL(self):
        if self.m_UserData != None :
            return self.m_UserData.URL
        else :
            return ""

    def changeUserName(self, name):
        name = str(name)
        
        try:
            conn = sqlite3.connect('Take6DataBase.db')
            c = conn.cursor()

            c.execute("UPDATE USER set NAME = '%s' where OPEN_ID='%s'" % (name, self.m_UserData.OpenID))
            conn.commit()
            print "Total number of rows updated :", conn.total_changes
        
            conn.close()
        except Exception,e:
            print 'error:',e
